<?php
/**
 * 队列操作静态类
 * @author ganxiangdong
 */
$hostName = gethostname();
if($hostName == 'web-01'){
	define('QUEUE_HOST', '192.168.0.1');
}else{
	define('QUEUE_HOST', '127.0.0.1');
}
/*方法返回的状态说明
 | HTTPSQS_PUT_END 队列已满（my god! 指定是你的出队列进程罢工了）
 | 
 |
 */

class Httpsqs
{
		//队列服务器地址
		private static $host = QUEUE_HOST;
		
		//队列服务器端口
        private static $port  = '1218'; 
        
        //认证密钥
        private static $auth = '';
        
        //默认为UTF-8
        private static $charset = '';
        
	    /**
	     * 入队
	     * @param unknown $queue_name
	     * @param unknown $queue_data
	     * @return boolean|unknown
	     */
	    public static function put($queue_name, $queue_data = array())
	    {
	    	$data = urlencode(json_encode($queue_data));
	        $result = self::http_post("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=put",$data);
            if ($result["data"] == "HTTPSQS_PUT_OK") {
                    return true;
            } else if ($result["data"] == "HTTPSQS_PUT_END") {
                    return $result["data"];
            }
            return false;
	    }
	    
	    /**
	     * 出队
	     * @param unknown $queue_name
	     * @return boolean|unknown
	     */
	    public static function get($queue_name)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=get");
			if ($result == false || $result["data"] == "HTTPSQS_ERROR" || $result["data"]=="HTTPSQS_GET_END" || $result["data"] == false) {
				return false;
			}
			return $result["data"];
	    }

	    /**
	     * 出队，并获取data和pos信息
	     * @param unknown $queue_name
	     * @return boolean|Ambigous <boolean, number>
	     */
	    public static function gets($queue_name)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=get");
	        if ($result == false || $result["data"] == "HTTPSQS_ERROR" || $result["data"] == false) {
	        	return false;
	        }
	        return $result;
	    }   
	        
	    /**
	     * 获取某队列状态
	     * @param unknown $queue_name
	     * @return boolean|Ambigous <>
	     */
	    public static function status($queue_name)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=status");
	                if ($result == false || $result["data"] == "HTTPSQS_ERROR" || $result["data"] == false) {
	                        return false;
	                }
	        return $result["data"];
	    }
	        
	    /**
	     * 查看队列某位置点的内容（注意，如果到了下一轮队列会发生覆盖现象）
	     * @param unknown $queue_name
	     * @param unknown $queue_pos
	     * @return boolean|unknown
	     */
	    public static function view($queue_name, $queue_pos)
	    {
	        $result = self::$http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=view&pos=".$queue_pos);
			if ($result == false || $result["data"] == "HTTPSQS_ERROR" || $result["data"] == false) {
				return false;
			}
	        return $result["data"];
	    }

	    /**
	     * 重置某队列（清空某队列）
	     * @param unknown $queue_name
	     * @return boolean
	     */
	    public static function reset($queue_name)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=reset");
	                if ($result["data"] == "HTTPSQS_RESET_OK") {
	                        return true;
	                }
	        return false;
	    }
	    
	    /**
	     * 设置某队列最大队列数量
	     * @param unknown $queue_name
	     * @param unknown $num
	     * @return boolean
	     */
	    public static function maxqueue($queue_name, $num)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=maxqueue&num=".$num);
	                if ($result["data"] == "HTTPSQS_MAXQUEUE_OK") {
	                        return true;
	                }
	        return false;
	    }
	        
	    /**
	     * 以Json的形式查看某队列状态
	     * @param unknown $queue_name
	     * @return boolean|Ambigous <>
	     */
	    public static function status_json($queue_name)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=".$queue_name."&opt=status_json");
	                if ($result == false || $result["data"] == "HTTPSQS_ERROR" || $result["data"] == false) {
	                        return false;
	                }
	        return $result["data"];
	    }
	
	    /**
	     * 不停止服务的情况下，修改定时刷新内存缓冲区内容到磁盘的间隔时间
	     * @param unknown $num	秒数
	     * @return boolean
	     */
	    public static function synctime($num)
	    {
	        $result = self::http_get("/?auth=".self::$auth."&charset=".self::$charset."&name=httpsqs_synctime&opt=synctime&num=".$num);
	                if ($result["data"] == "HTTPSQS_SYNCTIME_OK") {
	                        return true;
	                }
	        return false;
	    }
	    
	    /**
	     * GET方式请求接口
	     * @param unknown $query	url的query部分
	     * @return boolean|number
	     */
	    private static function http_get($query)
	    {
	    	$socket = fsockopen(self::$host, self::$port, $errno, $errstr, 5);
	    	if (!$socket)
	    	{
	    		return false;
	    	}
	    	$out = "GET ${query} HTTP/1.1\r\n";
	    	$out .= 'Host: '.self::$host.'\r\n';
	    	$out .= "Connection: close\r\n";
	    	$out .= "\r\n";
	    	fwrite($socket, $out);
	    	$line = trim(fgets($socket));
	    	$header = $line;
	    	list($proto, $rcode, $result) = explode(" ", $line);
	    	$len = -1;
	    	while (($line = trim(fgets($socket))) != "")
	    	{
	    		$header .= $line;
	    		if (strstr($line, "Content-Length:"))
	    		{
	    			list($cl, $len) = explode(" ", $line);
	    
	    		}
	    		if (strstr($line, "Pos:"))
	    		{
	    			list($pos_key, $pos_value) = explode(" ", $line);
	    		}
	    		if (strstr($line, "Connection: close"))
	    		{
	    			$close = true;
	    		}
	    	}
	    	if ($len < 0)
	    	{
	    		return false;
	    	}
	    	 
	    	$body = fread($socket, $len);
	    	$fread_times = 0;
	    	while(strlen($body) < $len){
	    		$body1 = fread($socket, $len);
	    		$body .= $body1;
	    		unset($body1);
	    		if ($fread_times > 100) {
	    			break;
	    		}
	    		$fread_times++;
	    	}
	    	//if ($close) fclose($socket);
	    	fclose($socket);
	    	$result_array["pos"] = !empty($pos_value)?(int)$pos_value:-1;
	    	$result_array["data"] = $body;
	    	return $result_array;
	    }
	    
	    /**
	     * POST方式请求接口
	     * @param unknown $query 请求query部分
	     * @param unknown $body		请求参数部分
	     * @return boolean|number
	     */
	    private static function http_post($query, $body)
	    {
	    	$socket = fsockopen(self::$host, self::$port, $errno, $errstr, 1);
	    	if (!$socket)
	    	{
	    		return false;
	    	}
	    	$out = "POST ${query} HTTP/1.1".PHP_EOL;
	    	$out .= 'Host: '.self::$host.PHP_EOL;
	    	$out .= "Content-Length: " . strlen($body) . PHP_EOL;
	    	$out .= "Connection: close".PHP_EOL;
	    	$out .= PHP_EOL;
	    	$out .= $body;
	    	fwrite($socket, $out);
	    	$line = trim(fgets($socket));
	    	$header = $line;
	    	list($proto, $rcode, $result) = explode(" ", $line);
	    	$len = -1;
	    	while (($line = trim(fgets($socket))) != "")
	    	{
	    		$header .= $line;
	    		if (strstr($line, "Content-Length:"))
	    		{
	    			list($cl, $len) = explode(" ", $line);
	    		}
	    		if (strstr($line, "Pos:"))
	    		{
	    			list($pos_key, $pos_value) = explode(" ", $line);
	    		}
	    		if (strstr($line, "Connection: close"))
	    		{
	    			$close = true;
	    		}
	    	}
	    	if ($len < 0)
	    	{
	    		return false;
	    	}
	    	$body = @fread($socket, $len);
	    	fclose($socket);
	    	$result_array["pos"] = !empty($pos_value)?(int)$pos_value:-1;
	    	$result_array["data"] = $body;
	    	return $result_array;
	    }
}